package ce.com.cenewbluesdk.scan;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.os.Handler;
import android.os.Message;

/**
 * Created by Administrator on 2016/11/8 0008.
 */
public class CEScanDev_4 extends CEScanDevBase {


    Handler handler = new Handler();

    private boolean isScan;
    private BluetoothManager manager;
    private BluetoothAdapter adapter;
    private BluetoothAdapter.LeScanCallback startLeScan = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            findDev(device, rssi, scanRecord);
        }
    };

    public CEScanDev_4(Context context, FindBlueTooth findDev) {
        super(context, findDev);
        manager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
        adapter = manager.getAdapter();
    }

    @Override
    public void startScan() {
        handler.removeCallbacks(stopScanRun);
        handler.postDelayed(stopScanRun, 12000);
        if (isScan) {
            return;
        }
        isScan = true;
        adapter.startLeScan(startLeScan);
    }

    @Override
    public void stopScan() {
        if (!isScan) {
            return;
        }
        isScan = false;
        adapter.stopLeScan(startLeScan);

    }


    StopScanRun stopScanRun = new StopScanRun();

    class StopScanRun implements Runnable {
        @Override
        public void run() {
            stopScan();
        }
    }
    /**
     * 蓝牙是否打开
     * @return
     */
    @Override
    public synchronized boolean isBleEnabled() {
        if (adapter == null)
            return false;

        return adapter.isEnabled();
    }

}
